package com.tang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tang.dto.BookDTO;
import com.tang.util.DeepBeanUtils;
import com.tang.vo.Book;
import com.tang.service.BookService;
import com.tang.mapper.BookMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author tang
* @description 针对表【ebook(电子书)】的数据库操作Service实现
* @createDate 2023-04-25 19:36:37
*/
@Slf4j
@Service
public class BookServiceImpl implements BookService{
    @Autowired
    private BookMapper bookMapper;

    @Override
    public List<BookDTO> all() {
        QueryWrapper<Book> wrapper=new QueryWrapper<>();
        List<Book> books = bookMapper.selectList(wrapper);
        List<BookDTO> bookDTOS = DeepBeanUtils.copyListProperties(books, BookDTO::new);
        return bookDTOS;
    }

    @Override
    public Map<String,Object> list(String category2Id, String name, int pageNum, int pageSize) {
        QueryWrapper<Book> wrapper=new QueryWrapper<>();
        Map<String,Object> map=new HashMap<>();
        if (ObjectUtils.isNotEmpty(category2Id)){
            wrapper.eq("category2_id", category2Id);
        }
        if (ObjectUtils.isNotEmpty(name)){
            wrapper.like("name",name);
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Book> books = bookMapper.selectList(wrapper);
        PageInfo<Book> pageInfo=new PageInfo<>(books);
        List<BookDTO> bookDTOS = DeepBeanUtils.copyListProperties(books, BookDTO::new);
        map.put("data",bookDTOS);
        map.put("total",pageInfo.getTotal());
        map.put("pages",pageInfo.getPages());
        return map;
    }

    @Override
    public int update(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO,book);
        if (ObjectUtils.isNotEmpty(bookDTO.getId())&&!bookDTO.getId().equals("0")){
            return bookMapper.updateById(book);
        }
        book.setId(null);
        return bookMapper.insert(book);
    }

    @Override
    public int delete(String id) {
        if (ObjectUtils.isNotEmpty(id)){
            return bookMapper.deleteById(id);
        }
        return 0;
    }
}




